package share

import (
	"fmt"
	"time"

	"clouds.lgb24kcs.cn/controllers/share/request"
	"clouds.lgb24kcs.cn/errorx"
	"clouds.lgb24kcs.cn/global"
	"clouds.lgb24kcs.cn/models"
	"clouds.lgb24kcs.cn/utils"
	"clouds.lgb24kcs.cn/utils/oss"
	"github.com/gin-gonic/gin"
)

type ShareCreateAPI struct {
}

var ShareAPI ShareCreateAPI

func (s *ShareCreateAPI) Create(c *gin.Context, req request.ShareCreateReq, userId int64) {

	api := oss.OSS{}
	bucketInfo := models.Storage{}
	tx := global.APP.DB.Where("userid=? and bucketname=?", userId, req.BucketName).First(&bucketInfo)
	if tx.Error != nil {
		global.APP.Log.Error(tx.Error.Error())
		utils.Fail(c, errorx.ShareCreate, "分享失败")
	} else {
		client := api.NewClient(bucketInfo.Accesskey, bucketInfo.Secretkey, bucketInfo.Zone)
		duration := time.Duration(req.Expiration) * time.Second // 将int64 转换为time.Duration

		presignedURL, err := api.ShareFile(client, req.BucketName, req.CatalogueName+"/"+req.ObjectName, duration)
		if err != nil {
			global.APP.Log.Error(err.Error())
		} else {
			fmt.Printf("presignedURL: %v\n", presignedURL)
			fmt.Println("ShareName: ", req.BucketName+"/"+req.CatalogueName+"/"+req.ObjectName)
			share := models.Share{
				ShareName:  req.BucketName + "/" + req.CatalogueName + "/" + req.ObjectName,
				Expiration: req.Expiration,
				ShareURL:   presignedURL,
				UserID:     userId,
			}
			tx = global.APP.DB.Create(&share)
			if tx.Error != nil {
				global.APP.Log.Error(tx.Error.Error())
				utils.Fail(c, errorx.ShareCreate, "分享失败")
			} else {
				utils.Success(c, 0, request.ListsResp{
					ShareName:  req.ObjectName,
					Expiration: req.Expiration,
					ShareURL:   presignedURL,
					CreateAt:   share.CreatedAt.Format(time.DateTime),
				})
			}
		}

	}
}
